﻿using UnityEngine;
using System.Collections;
using DG.Tweening;
using System;
/// <summary>
/// 角色脚本控制器
/// </summary>
public class RoleInSuperMarketCtrl :MonoSingleton<RoleInSuperMarketCtrl>
{
    Animator anim;
    private readonly int speedID = Animator.StringToHash("speed");

    //购物车  放置物品位置
    /* 0.11,0.24,0.08;  -0.028,0.24,0.08;  -0.14,0.24,0.08;
            0.29 0.04
            0.34 0
            0.39 -0.04
            0.44 -0.08
    */
    public Transform shoppingCar;
    Vector3 orgCarPos;
    Quaternion orgCarRot;
    //Vector3 cameraOrgPos = new Vector3(-0.12f, 2.45f, 9.39f);

    public float smoothing = 5f;

    float walkInPosZ = -0.281f;//0; 

    //人物是否可以跟随摄像机
    public bool isFollowCam = false;
    //是否走动
    bool isMove = false;
    float targetFollowPosX = 0f;

    private Action aniCallback;

    //星星绽放特效
    GameObject tx_502004083;

    //在购买物品操作过程中 没完成之前不允许再其他购买，以防止无限买入某个物品(当前只能有一个物品进行操作)
    public bool isCanOperateGoods = false;
    // Use this for initialization
    protected override void Awake()
    {
        transform.position = new Vector3(1.32f, 0f, -4.33f);
        anim = GetComponent<Animator>();
        shoppingCar = transform.Find("shoppingcar");
        if (SuperMarketGame.Instance.CurRoleType != RoleType.nuowa)
        {
            transform.localScale = new Vector3(0.022f, 0.022f, 0.022f);
            //Debug.LogError(shoppingCar.name);
            shoppingCar.localScale = new Vector3(47.7273f, 47.7273f, 47.7273f);
        }
        else
        {
            transform.localScale = Vector3.one;
            shoppingCar.localScale = new Vector3(1f,0.94f,1f);
        }
        orgCarPos = shoppingCar.localPosition;
        orgCarRot = shoppingCar.localRotation;

        SuperMarketGame.Instance.InitCarPoints(shoppingCar);
    }

    private void Start()
    {
 
    }

    void Update()
    {
        /*if (Input.GetKeyDown(KeyCode.Keypad0))
        {
            SetRoleAnim(0);
        }
        else if (Input.GetKeyDown(KeyCode.Keypad1))
            SetRoleAnim(1);
        else if (Input.GetKeyDown(KeyCode.Keypad2))
            SetRoleAnim(2);
        else if (Input.GetKeyDown(KeyCode.Keypad3))
            SetRoleAnim(3);
        else if (Input.GetKeyDown(KeyCode.Keypad4))
            SetRoleAnim(4);*/
    }
    /// <summary>
    /// 走进超市
    /// </summary>
    public void WalkInSide()
    {
        //Debug.Log("WalkInSide");
        //在点击完ShoppingList面板的 bg后 启用
        SuperMarketGame.Instance.DragScceneEnable(false);
        //anim.CrossFade("walk", 0.2f);
        SetRoleAnim(1);
        transform.DOLocalMoveZ(walkInPosZ, 2.6f).SetEase(Ease.Linear).OnComplete(()=> {
            //anim.CrossFade("idell", 0.2f);
            //Debug.Log("DOLocalMoveZ");
            SetRoleAnim(0);
            SuperMarketGame.Instance.soundCtrl.PlayRoleSound(RoleSoundType.IWantBuy);
            SuperMarketGame.Instance.OpenShoppingView();
        });
        Invoke("CloseTheDoor", 1.8f);
    }
    public void WalkInCenter()
    {
        //播放特效  0.58   0.5   0
        SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_603010109);
        if (tx_502004083 == null)
        {
            tx_502004083 = Instantiate(ResourceManager.Instance.GetResource("Effect/502004083", typeof(GameObject), enResourceType.Prefab, false, false).m_content as GameObject);
            tx_502004083.transform.SetParent(shoppingCar);
            tx_502004083.transform.localPosition = new Vector3(0.334f, 0.5f, 0);
            ParticleSystem ps = tx_502004083.transform.GetChild(0).GetComponent<ParticleSystem>();
            var main = ps.main;
            main.startSize = 0.25f;
            tx_502004083.SetActive(true);
            StartCoroutine(TimeUtility.DelayInvoke(1f, () =>
            {
                tx_502004083.SetActive(false);
            }));
        }

        SuperMarketGame.Instance.DragScceneEnable(false);
        SetRoleAnim(2);
        //Debug.Log("1111");
        StartCoroutine("ChangAnim");
        //Debug.Log("4444");
        
    }   
    IEnumerator ChangAnim()
    {
        AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
        //Debug.Log(info.normalizedTime + " == 2222  ");
        //Debug.Log(anim.GetCurrentAnimatorClipInfo(0)[0].clip);
        while (!info.IsName("hands_Standby_A"))
        {
            //Debug.Log(anim.GetCurrentAnimatorClipInfo(0)[0].clip + " == 3333 infoname");
            info = anim.GetCurrentAnimatorStateInfo(0);
            yield return 0;            
        }
        //Debug.Log("55555");
        /*SetRoleAnim(4);
        transform.DOLocalMove(new Vector3(0, 0, 0), 2f).OnComplete(() => {
            SetRoleAnim(3);
            isFollowCam = true;
            SuperMarketGame.Instance.DragScceneEnable(true);
            StopCoroutine(ChangAnim());
        });*/
        SetRoleAnim(3);
        //调整摄像机位置
        isFollowCam = true;

        SuperMarketGame.Instance.MoveMainCamera(-6.13f, () => {//-3.5f
            SuperMarketGame.Instance.DragScceneEnable(true);                       
            //指引
            SuperMarketGame.Instance.GuidBuyGoods();
            //动画有0.3秒   
            Invoke("InvokeOPerateGoods", 0.3f);
        },1.96f,6.21f,2.5f);

        StopCoroutine("ChangAnim");
    }

    void InvokeOPerateGoods()
    {
        isCanOperateGoods = true;
    }

    public void PlayCarEffect()
    {
        SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.COMMON_SOUND+ "601010110");
        tx_502004083.transform.localPosition = new Vector3(0.018f, 0.3f, 0f);
        tx_502004083.SetActive(true);
        StartCoroutine(TimeUtility.DelayInvoke(0.6f, () =>
        {
            tx_502004083.SetActive(false);
        }));
    }

    void CloseTheDoor()
    {
        SuperMarketGame.Instance.CloseTheDoor();
    }
 

    public void SetRoleAnim(int value, Action _aniCallback = null)
    {
        //Debug.Log(value + " == SetRoleAnim value");        
        anim.SetInteger(speedID, value);
        /*if (value == 5 || value == 6 || value == 7)
        {
            aniCallback = _aniCallback;

            SuperMarketGame.Instance.DragScceneEnable(false);
            StartCoroutine("ChangAnimMood", value); 
        }*/
    }
   
    /// <summary>
    /// 是否完成播放主角表情动画  用来控制拖拽物品时，需要等到表情播放完成再进行拖拽，
    /// 不然会出现（1 拖拽没有播放动画，2 拖拽还没完成又进行拖拽，在拖拽时候 DragScceneEnable(true) 被上个拖拽的动画设置为true了，此时可以
    /// 进行拖拽物品 并 改变位置SuperMarketGame 的位移，还可能造成，改变位置SuperMarketGame Input.GetMouseButtonUp(0)的禁止动画 设置为站立状态
    /// 导致无法切换一直循环，所以需要在进行动画切换的时候控制不能 进行位移和有其他地方修改动画状态）
    /// </summary>
    public bool IsFinishPlayAniMod
    {
        get {
            AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
            Debug.Log(info.IsName("hands_Standby_A").ToString() + "  === info ");
            return info.IsName("hands_Standby_A");//!info.IsName("happy_nod_A") && !info.IsName("Shake_head_A") && !info.IsName("happy_cheers_A");
        }       
    }
 
    //(拖拽)标示位  判断是否执行完成（由于可以开多个协程，所以会导致 偶然性 状态切换 一直在走切换不了3）
    private bool isPlayingAnimMod = false;
    IEnumerator ChangAnimMood(int value)
    {
        Debug.Log(value + " == SetRoleAnim value 2222222 ,isPlayingAnimMod == "+ isPlayingAnimMod);
        while (isPlayingAnimMod)
        {
            yield return 0;
        }
        isPlayingAnimMod = true;
        //isCanOperateGoods = false;

        string playName = "";
        if (value == 5)
            playName = "happy_nod_A";
        else if(value == 6)
            playName = "Shake_head_A";
        else if (value == 7)
            playName = "happy_cheers_A";
        AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
       
        Debug.Log("  playName =====  " + playName);
        while (!info.IsName(playName))
        {
            Debug.Log(anim.GetCurrentAnimatorClipInfo(0)[0].clip + " == 111 info.length");
            info = anim.GetCurrentAnimatorStateInfo(0);
            yield return 0;
        }
        //Debug.Log("info.length === " + anim.GetCurrentAnimatorClipInfo(0)[0].clip.length);
        info = anim.GetCurrentAnimatorStateInfo(0);
        while (info.normalizedTime < 1f && info.IsName(playName))
        {
            Debug.Log(info.normalizedTime + " == 222 info.length  , "+ anim.GetCurrentAnimatorClipInfo(0)[0].clip);
            info = anim.GetCurrentAnimatorStateInfo(0);
            yield return 0;
        }
        Debug.Log(" Finish ==== SetRoleAnim ======================= ");
        
        SuperMarketGame.Instance.DragScceneEnable(true);
        if (aniCallback != null)
            aniCallback();

        isPlayingAnimMod = false;
        //isCanOperateGoods = true;
        if (value != 7)
            SetRoleAnim(3);
        else
        {           
            StopCoroutine("ChangAnimMood");     
        }
    }

    public void RoleFollow(bool _isMove, float _targetFollowPosX, float _roleRotate, float _smoothing)
    {
        Debug.Log(" RoleFollow  == "+ isPlayingAnimMod.ToString());
        smoothing = _smoothing;
        isMove = _isMove;
        targetFollowPosX = _targetFollowPosX;
        //transform.rotation = Quaternion.Euler(new Vector3(transform.localEulerAngles.x, _roleRotate, transform.localEulerAngles.z));
        RotateRole(_roleRotate);
        if (isMove && isCanOperateGoods)//&& !isPlayingAnimMod
        {
            SetRoleAnim(4);
            Vector3 targetRole = new Vector3(targetFollowPosX, transform.position.y, transform.position.z);
            transform.position = Vector3.MoveTowards(transform.position, targetRole, Time.deltaTime * smoothing);
        }
    }

    public void RotateRole(float _roleRotate)
    {
        /*Quaternion tempQua1 = transform.rotation;
        Quaternion tempQua2 = Quaternion.Euler(new Vector3(0, _roleRotate, 0));        
        if (tempQua1 == tempQua2) return;
        transform.rotation = Quaternion.Euler(new Vector3(transform.localEulerAngles.x, _roleRotate, transform.localEulerAngles.z));*/
        float scaleZ = transform.localScale.z;
        if (scaleZ != _roleRotate)
        {
            transform.localScale = new Vector3(transform.localScale.x, transform.localScale.y, _roleRotate);
            //SuperMarketGame.Instance.CheckGoodsRotate(_roleRotate);
        }
    }

    public void ResetCarPos()
    {
        shoppingCar.localPosition = orgCarPos;
        shoppingCar.localRotation = orgCarRot;
    }
}
